import {Ionicons} from '@expo/vector-icons';
import {useRouter} from 'expo-router';
import React, {useEffect, useState} from 'react';
import {Alert, Button, Dimensions, Modal, StyleSheet, Text, TouchableOpacity, View} from 'react-native';

import FaceCheck from '@/components/FaceCheck';
import {ThemedText} from '@/components/ThemedText';
import {ThemedView} from '@/components/ThemedView';
import {checkFaceRN, UserVo} from '@/utils/api';
import {useImmersive} from '@/utils/ImmersiveContext';
import {useMode} from '@/utils/ModeContext';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {useNavigation} from 'expo-router';
import {useTestResults} from "@/contexts/TestResultsContext";

const {width} = Dimensions.get('window');

// 自定义确认弹窗组件
interface ConfirmModalProps {
    visible: boolean;
    nickname: string;
    mobile: string;
    onCancel: () => void;
    onConfirm: () => void;
}

function ConfirmModal({visible, nickname, mobile, onCancel, onConfirm}: ConfirmModalProps) {
    return (
        <Modal visible={visible} transparent animationType="fade">
            <View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.4)', justifyContent: 'center', alignItems: 'center'}}>
                <View
                    style={{backgroundColor: '#fff', borderRadius: 16, padding: 24, width: 300, alignItems: 'center'}}>
                    <Text
                        style={{fontSize: 20, fontWeight: 'bold', marginBottom: 16, color: '#0a7ea4'}}>请确认信息</Text>
                    <Text style={{fontSize: 16, marginBottom: 8, color: '#333'}}>昵称：{nickname}</Text>
                    <Text style={{fontSize: 16, marginBottom: 8, color: '#333'}}>电话：{mobile}</Text>
                    <View style={{flexDirection: 'row', marginTop: 24}}>
                        <TouchableOpacity style={{
                            flex: 1,
                            marginRight: 8,
                            padding: 12,
                            borderRadius: 8,
                            backgroundColor: '#eee',
                            alignItems: 'center'
                        }} onPress={onCancel}>
                            <Text style={{color: '#666', fontWeight: 'bold'}}>取消</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={{
                            flex: 1,
                            marginLeft: 8,
                            padding: 12,
                            borderRadius: 8,
                            backgroundColor: '#0a7ea4',
                            alignItems: 'center'
                        }} onPress={onConfirm}>
                            <Text style={{color: '#fff', fontWeight: 'bold'}}>确认</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        </Modal>
    );
}

export default function HomeScreen() {
    const router = useRouter();
    const {userMode, isEnterpriseMode, isPersonalMode, setUserMode} = useMode();
    const [faceModalVisible, setFaceModalVisible] = useState(false);
    const [faceVerified, setFaceVerified] = useState(false);
    const [isFaceChecking, setIsFaceChecking] = useState(false);
    const [confirmModalVisible, setConfirmModalVisible] = useState(false);
    const {clearAllResults} = useTestResults();
    const [confirmInfo, setConfirmInfo] = useState({nickname: '', mobile: ''});
    const {setIsImmersive} = useImmersive();
    const navigation = useNavigation();

    useEffect(() => {
        const loadMode = async () => {
            const mode = await AsyncStorage.getItem('MODE');
            if (mode === 'enterprise' || mode === 'personal') {
                setUserMode(mode);
            } else {
                // 如果没有选择模式，重定向到模式选择页面
                router.replace('/mode-selection');
            }
        };
        loadMode();
        setIsImmersive(false); // Always immersive off for home screen
        return () => setIsImmersive(false);
    }, []);

    // 隐藏TabBar
    React.useEffect(() => {
        router.setParams?.({tabBarStyle: undefined});
    }, []);

    const handleStartExamination = async () => {
        clearAllResults();
        if (isPersonalMode) {
            await AsyncStorage.setItem('TEST_USER', await AsyncStorage.getItem('USER') as string);
            router.push('/examination');
        } else {
            setFaceModalVisible(true);
        }
    };

    const handleFaceDetected = async (imagePath: string) => {
        if (isFaceChecking) return;
        setIsFaceChecking(true);
        try {
            const res = await checkFaceRN(imagePath);
            const user: UserVo = res.data
            if (!!user.id) {
                console.log(user)
                await AsyncStorage.setItem('TEST_USER', JSON.stringify(user));
                setConfirmInfo({nickname: user.nickname, mobile: user.mobile});
                setConfirmModalVisible(true);
            } else {
                Alert.alert('人脸识别失败', res?.message || '请重试');
            }
        } catch (e: any) {
            Alert.alert('人脸识别失败', e.message || '请重试');
        } finally {
            setIsFaceChecking(false);
        }
    };

    const handleModeSelect = async (mode: 'enterprise' | 'personal') => {
        await AsyncStorage.setItem('MODE', mode);
        await AsyncStorage.setItem('userMode', mode);
        setUserMode(mode);
    };

    return (
        <ThemedView style={styles.container}>
            {/* 标题区域 */}
            <ThemedView style={styles.headerContainer}>
                <ThemedText type="title" style={styles.title}>
                    岗前安全健康速测仪
                </ThemedText>
                <ThemedText style={styles.subtitle}>
                    专业的安全健康检测设备
                </ThemedText>
            </ThemedView>

            {/* 模式选择卡片 */}
            <ThemedView style={styles.modeDisplayContainer}>
                <ThemedText type="subtitle" style={styles.modeSelectionTitle}>
                    选择检测模式
                </ThemedText>
                <ThemedView style={styles.modeCardsContainer}>
                    {/* 企业模式卡片 */}
                    <TouchableOpacity
                        style={[
                            styles.modeCard,
                            isEnterpriseMode && styles.selectedModeCard
                        ]}
                        onPress={() => handleModeSelect('enterprise')}
                        activeOpacity={0.8}
                    >
                        <ThemedView style={[
                            styles.modeIconContainer,
                            isEnterpriseMode && styles.selectedModeIconContainer
                        ]}>
                            <Ionicons
                                name="business"
                                size={28}
                                color={isEnterpriseMode ? "#ffffff" : "#0a7ea4"}
                            />
                        </ThemedView>
                        <ThemedText style={[
                            styles.modeTitle,
                            isEnterpriseMode && styles.selectedModeTitle
                        ]}>
                            企业模式
                        </ThemedText>
                        <ThemedText style={[
                            styles.modeDescription,
                            isEnterpriseMode && styles.selectedModeDescription
                        ]}>
                            适用于企业员工岗前健康检查
                        </ThemedText>
                        {isEnterpriseMode && (
                            <ThemedView style={styles.selectedIndicator}>
                                <Ionicons name="checkmark" size={16} color="#ffffff"/>
                            </ThemedView>
                        )}
                    </TouchableOpacity>

                    {/* 个人模式卡片 */}
                    <TouchableOpacity
                        style={[
                            styles.modeCard,
                            isPersonalMode && styles.selectedModeCard
                        ]}
                        onPress={() => handleModeSelect('personal')}
                        activeOpacity={0.8}
                    >
                        <ThemedView style={[
                            styles.modeIconContainer,
                            isPersonalMode && styles.selectedModeIconContainer
                        ]}>
                            <Ionicons
                                name="person"
                                size={28}
                                color={isPersonalMode ? "#ffffff" : "#0a7ea4"}
                            />
                        </ThemedView>
                        <ThemedText style={[
                            styles.modeTitle,
                            isPersonalMode && styles.selectedModeTitle
                        ]}>
                            个人模式
                        </ThemedText>
                        <ThemedText style={[
                            styles.modeDescription,
                            isPersonalMode && styles.selectedModeDescription
                        ]}>
                            适用于个人健康自测
                        </ThemedText>
                        {isPersonalMode && (
                            <ThemedView style={styles.selectedIndicator}>
                                <Ionicons name="checkmark" size={16} color="#ffffff"/>
                            </ThemedView>
                        )}
                    </TouchableOpacity>
                </ThemedView>
            </ThemedView>

            {/* 快速操作区域 */}
            <ThemedView style={styles.actionContainer}>
                <TouchableOpacity
                    style={styles.startButton}
                    onPress={handleStartExamination}
                    activeOpacity={0.8}
                >
                    <View style={styles.startButtonContent}>
                        <Ionicons name="play" size={24} color="#ffffff"/>
                        <Text style={styles.startButtonText}>
                            开始检测
                        </Text>
                    </View>
                </TouchableOpacity>
            </ThemedView>

            {/* 底部信息 */}
            <ThemedView style={styles.footerContainer}>
                <ThemedText style={styles.footerText}>
                    安全健康检测专家
                </ThemedText>
                <ThemedText style={styles.footerSubText}>
                    专业 · 安全 · 可靠
                </ThemedText>
            </ThemedView>

            {/* 人脸识别弹窗始终可用 */}
            <Modal visible={faceModalVisible} transparent animationType="slide">
                <View style={{
                    flex: 1,
                    backgroundColor: 'rgba(0,0,0,0.5)',
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                    <View style={{
                        width: 340,
                        height: 420,
                        backgroundColor: '#fff',
                        borderRadius: 16,
                        overflow: 'hidden',
                        padding: 8
                    }}>
                        <FaceCheck
                            onFaceDetected={handleFaceDetected}
                            detectionInterval={3000}
                        />
                        <Button title="取消" onPress={() => setFaceModalVisible(false)}/>
                    </View>
                </View>
            </Modal>
            <ConfirmModal
                visible={confirmModalVisible}
                nickname={confirmInfo.nickname}
                mobile={confirmInfo.mobile}
                onCancel={() => setConfirmModalVisible(false)}
                onConfirm={() => {
                    setConfirmModalVisible(false);
                    setFaceVerified(true);
                    setFaceModalVisible(false);
                    router.push('/examination');
                }}
            />
        </ThemedView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 20,
        justifyContent: 'space-between',
    },
    headerContainer: {
        alignItems: 'center',
        marginTop: 60,
        marginBottom: 40,
    },
    title: {
        textAlign: 'center',
        marginBottom: 8,
        color: '#0a7ea4',
        fontWeight: 'bold',
    },
    subtitle: {
        textAlign: 'center',
        fontSize: 16,
        opacity: 0.8,
    },
    modeDisplayContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: 10,
    },
    modeSelectionTitle: {
        marginBottom: 24,
        color: '#0a7ea4',
        fontWeight: 'bold',
        textAlign: 'center',
    },
    modeCardsContainer: {
        flexDirection: 'row',
        gap: 16,
        justifyContent: 'center',
        alignItems: 'stretch',
    },
    modeCard: {
        backgroundColor: '#ffffff',
        borderRadius: 16,
        padding: 20,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 4,
        },
        shadowOpacity: 0.15,
        shadowRadius: 8,
        elevation: 8,
        borderWidth: 2,
        borderColor: 'rgba(10, 126, 164, 0.2)',
        flex: 1,
        maxWidth: 150,
        position: 'relative',
    },
    selectedModeCard: {
        backgroundColor: '#0a7ea4',
        borderColor: '#0a7ea4',
    },
    modeIconContainer: {
        width: 50,
        height: 50,
        borderRadius: 25,
        backgroundColor: 'rgba(10, 126, 164, 0.1)',
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 12,
    },
    selectedModeIconContainer: {
        backgroundColor: 'rgba(255, 255, 255, 0.2)',
    },
    modeTitle: {
        marginBottom: 8,
        color: '#0a7ea4',
        fontWeight: 'bold',
        fontSize: 16,
        textAlign: 'center',
    },
    selectedModeTitle: {
        color: '#ffffff',
    },
    modeDescription: {
        textAlign: 'center',
        lineHeight: 18,
        opacity: 0.8,
        fontSize: 12,
    },
    selectedModeDescription: {
        color: '#ffffff',
        opacity: 0.9,
    },
    selectedIndicator: {
        position: 'absolute',
        top: 10,
        right: 10,
        width: 24,
        height: 24,
        borderRadius: 12,
        backgroundColor: 'rgba(255, 255, 255, 0.3)',
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.5)',
    },
    actionContainer: {
        alignItems: 'center',
        marginBottom: 40,
    },
    startButton: {
        backgroundColor: '#0a7ea4',
        borderRadius: 12,
        paddingHorizontal: 32,
        paddingVertical: 16,
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 4,
        },
        shadowOpacity: 0.2,
        shadowRadius: 8,
        elevation: 8,
    },
    startButtonContent: {
        flexDirection: 'row',
        alignItems: 'center',
        gap: 8,
    },
    startButtonText: {
        color: '#ffffff',
        fontSize: 18,
        fontWeight: 'bold',
    },
    footerContainer: {
        alignItems: 'center',
        marginBottom: 20,
    },
    footerText: {
        fontSize: 12,
        opacity: 0.6,
        marginBottom: 4,
    },
    footerSubText: {
        fontSize: 10,
        opacity: 0.4,
    }
});
